/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import cn.hutool.core.map.MapUtil;
import me.zhengjie.modules.system.domain.IdentityOrder;
import me.zhengjie.modules.system.domain.UserChatOrder;
import me.zhengjie.modules.system.domain.WxUser;
import me.zhengjie.modules.system.service.WxUserService;
import me.zhengjie.modules.system.service.dto.IdentityOrderQueryCriteria;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.system.repository.UserChatOrderRepository;
import me.zhengjie.modules.system.service.UserChatOrderService;
import me.zhengjie.modules.system.service.dto.UserChatOrderDto;
import me.zhengjie.modules.system.service.dto.UserChatOrderQueryCriteria;
import me.zhengjie.modules.system.service.mapstruct.UserChatOrderMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author 王宇
* @date 2024-04-06
**/
@Service
@RequiredArgsConstructor
public class UserChatOrderServiceImpl implements UserChatOrderService {

    private final UserChatOrderRepository userChatOrderRepository;
    private final UserChatOrderMapper userChatOrderMapper;

    @Autowired
    private WxUserService wxUserService;

    @Override
    public Map<String,Object> queryAll(UserChatOrderQueryCriteria criteria, Pageable pageable){
        Page<UserChatOrder> page = userChatOrderRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        Page<UserChatOrderDto> map = page.map(userChatOrderMapper::toDto);
        List<UserChatOrderDto> content = map.getContent();
        Map<String,WxUser> userMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(content)){
            content.forEach(s -> {
                WxUser wxUser = userMap.get(s.getOpenId());
                if (Objects.isNull(wxUser)){
                    wxUser = wxUserService.findByOpenId(s.getOpenId());
                }
                if (Objects.nonNull(wxUser)){
                    s.setUserName(StringUtils.defaultIfBlank(wxUser.getRealName(),wxUser.getNickname()));
                    userMap.put(s.getOpenId(),wxUser);
                }
            });
        }
        return PageUtil.toPage(map);
    }

    @Override
    public List<UserChatOrderDto> queryAll(UserChatOrderQueryCriteria criteria){
        return userChatOrderMapper.toDto(userChatOrderRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public UserChatOrderDto findById(Long orderId) {
        UserChatOrder userChatOrder = userChatOrderRepository.findById(orderId).orElseGet(UserChatOrder::new);
        ValidationUtil.isNull(userChatOrder.getOrderId(),"UserChatOrder","orderId",orderId);
        return userChatOrderMapper.toDto(userChatOrder);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserChatOrderDto create(UserChatOrder resources) {
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        resources.setOrderId(snowflake.nextId()); 
        return userChatOrderMapper.toDto(userChatOrderRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(UserChatOrder resources) {
        UserChatOrder userChatOrder = userChatOrderRepository.findById(resources.getOrderId()).orElseGet(UserChatOrder::new);
        ValidationUtil.isNull( userChatOrder.getOrderId(),"UserChatOrder","id",resources.getOrderId());
        userChatOrder.copy(resources);
        userChatOrderRepository.save(userChatOrder);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long orderId : ids) {
            userChatOrderRepository.deleteById(orderId);
        }
    }

    @Override
    public void download(List<UserChatOrderDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (UserChatOrderDto userChatOrder : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("订单编号", userChatOrder.getOrderNo());
            map.put("openid", userChatOrder.getOpenId());
            map.put("预支付流水号", userChatOrder.getPrePayid());
            map.put("支付流水号", userChatOrder.getPaySerialid());
            map.put("支付金额", userChatOrder.getPayAmount());
            map.put("聊天金额", userChatOrder.getChatAmount());
            map.put("优惠金额", userChatOrder.getDiscountAmount());
            map.put("支付状态，0：未支付，1：已支付", userChatOrder.getPayStatus());
            map.put("更新时间", userChatOrder.getUpdateTime());
            map.put("创建时间", userChatOrder.getCreateTime());
            map.put("备注", userChatOrder.getRemark());
            map.put("类型 日/周/月/季/年", userChatOrder.getOrderType());
            map.put("业务ID", userChatOrder.getBizId());
            map.put("订单状态", userChatOrder.getOrderStatus());
            map.put("超时取消时间", userChatOrder.getExpireTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public UserChatOrder findOne(String orderSn) {
        UserChatOrderQueryCriteria criteria = new UserChatOrderQueryCriteria();
        criteria.setOrderNo(orderSn);
        List<UserChatOrder> all = userChatOrderRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder));
        if (CollectionUtils.isEmpty(all)){
            return null;
        }
        return all.get(0);
    }
}